define(['jquery', 'bootstrap', 'backend', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template', 'form'], function ($, undefined, Backend, Datatable, Table, Echarts, undefined, Template, Form) {

    var Controller = {
        index: function () {

            require.config({
                    paths: {
                        'Gzyechart': '../addons/workteam/js/gzyechart',
                    }
                }
            );
            require(['Gzyechart'], function () {
                Form.api.bindevent($("form[role=form]"));
                // 基于准备好的dom，初始化健康表格数据
                Gzyechart.echart.loadEchart("hours", Echartdata.hours.date, Echartdata.hours.data);
                Gzyechart.echart.initButton(function (data) {
                    Controller.api.statistics(data);
                });
                $(document).on("change", "#c-owner_user_id", function () {
                    var owner_user_id = $(this).val();
                    var datetimerange = $(this).parent().parent().find(".datetimerange");
                    var url = datetimerange.data('url');
                    if (url.indexOf("owner_user_id") != -1) {
                        url = Controller.api.replaceParamVal(url, "owner_user_id", owner_user_id);
                    } else {
                        url = url + "&owner_user_id=" + owner_user_id;
                    }
                    datetimerange.data('url', url);
                    Controller.api.datetimerange(datetimerange);
                });
                $(document).on("change", "#c-group_id", function () {
                    var group_id = $(this).val();
                    var datetimerange = $(this).parent().parent().parent().find(".datetimerange");
                    var url = datetimerange.data('url');
                    if (url.indexOf("group_id") != -1) {
                        url = Controller.api.replaceParamVal(url, "group_id", group_id);
                    } else {
                        url = url + "&group_id=" + group_id;
                    }
                    datetimerange.data('url', url);
                    Controller.api.datetimerange(datetimerange);
                });
                $("#c-group_id").trigger('change');

                Controller.api.loadLogEchart(log_echart,'hours-echart2');
                Controller.api.loadLogEchart(paylog_echart,'pay-echart');

                $(document).on("change", "#c-project_id", function () {
                    var project_id = $(this).val();
                    console.log(project_id);
                    $.ajax({
                        url : 'workteam/analysis/project/projectpaylog',
                        method : 'get',
                        data : {
                            project_id :project_id,
                        },
                        success : function(data) {
                            var data=data.data;
                            Controller.api.loadLogEchart(data.log_echart,'pay-echart');
                            $('#p_price').html(data.p_price);
                            var p_difference=parseFloat(data.p_price)+parseFloat(data.expenses);
                            $('#p_difference').html(p_difference);
                            $('#expenses').html(data.expenses);

                        },
                    });
                });


            });


        },
        lists: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workteam/analysis/project/lists' + location.search,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: 'workteam_project',
                }
            });

            var table = $("#workteam_project");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: '',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},

                        {field: 'number', title: __('项目编号'),operate: "LIKE", sortable: true},
                        {field: 'name', title: __('项目名称'),align: 'left',operate: "LIKE"
                            ,customField: 'level'
                            ,formatter: function (value, row, index) {
                                //判断是否逾期
                                var newtime = Math.round(new Date().getTime()/1000).toString();
                                if (newtime>row.end_time&&$.inArray(row.status,[2,3])==-1 )
                                    value='<span class="label label-danger">逾</span>'+value;
                                return value
                            }},
                        {field: 'padmin.nickname', title: __('项目经理'),operate:false},
                        {field: 'project_admin_id', title: __('项目经理'),addclass: 'selectpage',visible:false,
                            extend: "data-source='workteam/common/selectpage/model/admin/type/all' data-field='nickname'"},

                        {field: 'plan_hours', title: __('计划工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'actual_hours', title: __('实际工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'task_count', title: __('任务总量'), operate: 'BETWEEN', sortable: true},
                        {field: 'task_complate', title: __('完成数量'), operate: 'BETWEEN', sortable: true},
                        {field: 'admin_count', title: __('参与人数'), },
                        {field: 'price', title: __('金额'), operate: 'BETWEEN', sortable: true},
                        {field: 'expenses', title: __('支出'), operate: 'BETWEEN', sortable: true},
                        {
                            field: 'price_expenses',
                            title: __('收支差额'),
                            formatter: function (v, r) {
                                return parseFloat(r.price)+parseFloat(r.expenses);
                            },operate:false
                        },
                        {field: 'status', title: __('Status'), searchList: Config.statusList, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [

                                {
                                    name: 'task',
                                    text: __('添加支出'),
                                    title: __('添加支出'),
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'workteam/accountlog/add',

                                },

                            ]}
                    ]
                ],
                exportOptions: {
                    htmlContent: false,
                    onCellHtmlData: function (cell, row, col, data){//处理导出内容,自定义某一行、某一列、某个单元格的内容
                        return data;
                    },
                },

                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

          
        },

        api: {
            level: function (value, row, index, obj) {
                if (value == 1) return '';
                var colorArr = ["primary", "success", "default", "info", "warning", "danger", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];

                var field = obj.field;
                if (typeof obj.customField !== 'undefined' && typeof row[obj.customField] !== 'undefined') {
                    field = obj.customField;
                }
                var color = index > -1 && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                var icon = '', display = Config.levelList[value];
                var html = '<span class="label label-' + color + '">' + display + '</span>';
                if (obj.operate != false) {
                    html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + html + '</a>';
                }
                return html;
            },
            //替换指定传入参数的值,paramName为参数,replaceWith为新值
            replaceParamVal: function (oUrl, paramName, replaceWith) {
                var re = eval('/(' + paramName + '=)([^&]*)/gi');
                return oUrl.replace(re, paramName + '=' + replaceWith);
            },
            datetimerange: function (datetimerange) {

                var obj = $(datetimerange).data("daterangepicker");
                if (typeof obj == "undefined") return false
                Gzyechart.echart.refreshEchart(datetimerange.data('type'),
                    datetimerange.data('url'), obj.startDate.format(obj.locale.format),
                    obj.endDate.format(obj.locale.format), function (data) {
                        Controller.api.statistics(data);
                    }
                );
            },
            statistics: function (data) {

                if (data.code == 1) {
                    var tempdata = data.data.hours.data;
                    var count_expenses=Controller.api.sum(tempdata[__('支出金额')]);
                    var count_price=Controller.api.sum(tempdata[__('项目金额')]);
                    $('.count_expenses').html(count_expenses);
                    $('.count_price').html(count_price);
                    $('.price-expenses').html(count_price+count_expenses);
                    $('.count_project').html(Controller.api.sum(tempdata[__('完成项目')]));


                    Controller.api.loadLogEchart(data.data.log_echart,'hours-echart2');



                }else {
                    layer.msg(data.msg, {'icon':2});
                }


            },
            sum:function (arr) {
                var s = 0;
                arr.forEach(function(val, idx, arr) {
                    s += parseFloat(val);
                }, 0);
                return s;
            },
            loadLogEchart:function (log_echart,idstr) {
                var chartDom = document.getElementById(idstr);
                var myChart = Echarts.init(chartDom);
                var option;


                option = {
                    title: {
                        text: '支出类型统计',
                        subtext: '',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: 10,
                        top: 20,
                        bottom: 20,
                        data: log_echart.legendData
                    },
                    series: [
                        {
                            name: '',
                            type: 'pie',
                            radius: '55%',
                            center: ['40%', '50%'],
                            data: log_echart.seriesData,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                option && myChart.setOption(option);

            }

        }
    };

    return Controller;
});
